from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
from Screens.ChoiceBox import ChoiceBox
from Screens.EpgSelection import EPGSelection
from Screens.ChannelSelection import ChannelSelection, BouquetSelector
from Screens.TimerEntry import TimerEntry
from Plugins.Plugin import PluginDescriptor
from enigma import eTimer, eDVBDB
from enigma import eEPGCache, eListbox, eServiceCenter, eServiceReference
from Components.Input import Input
from Components.Pixmap import Pixmap
from Components.Label import Label
from Components.config import config
from Components.UsageConfig import preferredInstantRecordPath, defaultMoviePath
from Components.EpgList import EPGList, Rect
from Components.ConfigList import ConfigList, ConfigListScreen
from Components.ServiceList import ServiceList
from Components.ActionMap import ActionMap, NumberActionMap, HelpableActionMap
from Components.Button import Button
from Components.config import config, ConfigClock, ConfigSubsection, ConfigInteger, ConfigSelection, ConfigText, ConfigEnableDisable, KEY_LEFT, KEY_RIGHT, KEY_0, getConfigListEntry, ConfigNumber, ConfigBoolean
from time import time, localtime, strftime
from ServiceReference import ServiceReference
from RecordTimer import RecordTimerEntry, parseEvent, AFTEREVENT
from xml.dom.minidom import Document

from Plugins.Extensions import MediaPlayer
from Screens.InfoBarGenerics import InfoBarShowHide, InfoBarMenu, InfoBarInstantRecord, InfoBarTimeshift, InfoBarSeek, InfoBarTimeshiftState, InfoBarExtensions, InfoBarSubtitleSupport, InfoBarAudioSelection, InfoBarChannelSelection
from Components.ServiceEventTracker import ServiceEventTracker, InfoBarBase

import time
import socket
import threading

# OSAmi Demo Plugin
# Written by Samuli Heinonen and Olli Kuonanoja
# 	-Added SelectionBox 26.08.2010
#	-Added Socket Client communication 6.9.2010
#	-Added EPG data handling 14.9.2010
#	-Code clean up 16.9.2010
#	-fileWriter thread added 17.9.2010
#	-Autostart functionality added 11.10.2010
#	-Recording specified event in implementation 14.10.2010
#	-InstantRecording in implementation 12.11.2010
#	-Stop and Start service 16.11.2010

Session = None
Servicelist = None
man_bouquets = None
autostart = False
service_types_tv = '1:7:1:0:0:0:0:0:0:0:(type == 1) || (type == 17) || (type == 22) || (type == 25) || (type == 134) || (type == 195)'


#class MyInfoBarTimeshift(InfoBarTimeshift):
#	def __init__(self):
#		InfoBarTimeshift.__init__(self)
#		
#class MyInfoBarSeek(InfoBarSeek):
#	def __init__(self):
#		InfoBarSeek.__init__(self)
		
def main(session, servicelist, **kwargs):
	global Session
	global man_bouquets
	global Servicelist
	global Services
	global autostart
	autostart = False
	Session = session

	Servicelist = servicelist
	man_bouquets = Servicelist.getRoot()
	Services = getBouquetServices(man_bouquets)

	session.open(Communicator) #, session, services)


def sessionstart(reason, session):
	global Session
	global man_bouquets
	global Servicelist
	global Services
	global autostart
	autostart = True
	Session = session

	#Finding available services
	Servicelist = ServiceList()
	refstr = '%s ORDER BY name'%(service_types_tv)
	ref = eServiceReference(refstr)
	Servicelist.setRoot(ref, False)
	man_bouquets = Servicelist.getRoot()
	Services = getBouquetServices(man_bouquets)

	session.open(Communicator) #, session, service)


def Plugins(**kwargs):
	
	return [
		PluginDescriptor(name="OSAmI Communication Plugin", description="OSAmI is great", where = PluginDescriptor.WHERE_SESSIONSTART, fnc=sessionstart),
		PluginDescriptor(name="OSAmI Communication Plugin", description="OSAmI is great", where = PluginDescriptor.WHERE_EXTENSIONSMENU, fnc=main)
		]

def getBouquetServices(bouquet):
	services = [ ]
	Servlist = eServiceCenter.getInstance().list(bouquet)
	if not Servlist is None:
		while True:
			service = Servlist.getNext()
			if not service.valid(): #check if end of list
				break
			if service.flags & (eServiceReference.isDirectory | eServiceReference.isMarker): #ignore non playable services
				continue
			services.append(ServiceReference(service))
	return services
	
class Communicator(Screen, InfoBarBase, InfoBarShowHide, InfoBarMenu, \
		InfoBarInstantRecord, InfoBarSeek, InfoBarTimeshift, \
		InfoBarTimeshiftState, InfoBarExtensions, InfoBarSubtitleSupport, \
		InfoBarAudioSelection, InfoBarChannelSelection): #, ConfigListScreen):
	
	EMPTY = 0
	ADD_TIMER = 1
	REMOVE_TIMER = 2
	ZAP = 1
	
	def __init__(self, session, args=None): #, services, zapFunc=None, bouquetChangeCB=None, bouquetname=""):
		Screen.__init__(self, session)
		self.epgcache = eEPGCache.getInstance()
		self.testtimer = eTimer()
		self.testtimer.callback.append(self.connect)
		self.session = session
		
		for x in InfoBarBase, InfoBarShowHide, InfoBarMenu, \
				InfoBarInstantRecord, InfoBarSeek, InfoBarTimeshift, \
				InfoBarTimeshiftState, InfoBarSubtitleSupport, \
				InfoBarExtensions, InfoBarAudioSelection, InfoBarChannelSelection:
			x.__init__(self)
		
		#timeShifter = InfoBarTimeshift(self)
		#timeSeeker = InfoBarSeek(self)
		
		self.timeshift_enabled = 0
		
		#self.oldService = self.session.nav.getCurrentlyPlayingServiceReference()
		
		self.recording = []
		
		self["key_green"] = Button("Timer")
		self.key_red_choice = self.EMPTY
		self.key_green_choice = self.EMPTY
		self["oktext"] = Label(_("OK"))
		self["canceltext"] = Label(_("Cancel"))
		self["actions"] = ActionMap(["OkCancelActions", "HelpActions"],
		{
			"cancel": self.closeScreen,
			"ok": self.keyok,
		})
					
		if autostart:
			self.testtimer.start(8000, True)
		else:
			self.testtimer.start(60, True)
	
	def closeScreen(self):
		self.clean()
		#self.showMainMenu()
	
	def keyok(self):
		self.clean()
		#self.showMainMenu()
					
	def connect(self):
		global udp_port, port, host, sock, s
		udp_port = 6788
		host = '127.0.0.1'
		try:			
			# UDP socket communication
			s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
			port = int(udp_port)
			s.connect((host, port))
			s.sendall("Client: Creating pipe")
			#self.showMainMenu() # This is for testing only!
			
			socketThread = SocketThread(self.session, self)	#Creating socket communication thread
			socketThread.start()

		except socket.error, msg:
			self.session.open(MessageBox, "Socket error: "+str(msg), MessageBox.TYPE_ERROR)
			self.clean()
	
	def clean(self):
		global man_bouquets
		man_bouquets = None
		global Session
		Session = None
		global Servicelist
		Servicelist = None
		global Services
		Services = None
		self.close()
	
	def getServices(self, bouquet):
		services = [ ]
		Servlist = eServiceCenter.getInstance().list(bouquet)
		if not Servlist is None:
			while True:
				service = Servlist.getNext()
				if not service.valid(): #check if end of list
					break
				if service.flags & (eServiceReference.isDirectory | eServiceReference.isMarker): #ignore non playable services
					continue
				services.append(ServiceReference(service))
		return services
	
	def parseEvent(self, ev):
		name = ev.getEventName()
		description = ev.getShortDescription()
		begin = ev.getBeginTime()
		end = begin + ev.getDuration()
		eit = ev.getEventId()
		#begin -= config.recording.margin_before.value * 60
		#end += config.recording.margin_after.value * 60
		return (eit, name, description, begin, end)
	
	def showMainMenu(self):
	
		lista = [ 	('Send Message','Send Message'), 
				('Receive Message', 'Receive Message'),
				('Update EPG data','Update EPG data'),
				('Show Current Program','Show Current Program'),
				('Record Program','Record Program'),
				('Start InstantRecording','Start InstantRecording'),
				('Pause','Pause'),
				('Play','Play'),
				('Forward','Forward'),
				('Cancel','Cancel') 
				]
		self.session.openWithCallback(	self.mycallback,
						ChoiceBox,
						title = _("OSAmI Communication"),
						list = lista)
						

	def mycallback(self, choice):
		
		if choice:
		
			if str(choice[0]) == 'Send Message':
				self.sendMessage('Yes, my lord!')
				self.showAnyMessage("Message <Yes, my lord!> sent to: "+str(host)+":"+str(port))

			elif str(choice[0]) == 'Receive Message':
				self.recvMessage()

			elif str(choice[0]) == 'Update EPG data':
				self.updateEPG()

			elif str(choice[0]) == 'Show Current Program':
				self.showCurrentService()
			
			elif str(choice[0]) == 'Record Program':
				eventId = 638
				channel = 'Sub Juniori'
				self.timerAdd(eventId, channel)
			
			elif str(choice[0]) == 'Start InstantRecording':
				self.startInstantRecording()
			
			elif str(choice[0]) == 'Pause':
				#self.session.openWithCallback(self.showMainMenuCallback, self.pause)
				self.pause()
			
			elif str(choice[0]) == 'Play':
				#self.session.openWithCallback(self.showMainMenuCallback, self.play)
				self.play()
				
			elif str(choice[0]) == 'Forward':
				#self.session.openWithCallback(self.showMainMenuCallback, self.forward)
				self.forward()

			elif str(choice[0]) == 'Cancel':
				self.clean()
		
		else:
			self.clean()
	
	
	def sendMessage(self, message):
		# UDP socket communication
		try:
			s.connect((host, port))
			s.sendall(message)
			#s.sendto(message, (host, port))
			
		except socket.error, msg:
			self.session.openWithCallback(self.showMainMenuCallback, MessageBox, "Socket error: "+str(msg), MessageBox.TYPE_ERROR)
			#self.session.open(MessageBox, "Socket error: "+str(msg), MessageBox.TYPE_ERROR)
	
	def recvMessage(self):
		# UDP socket communication
		try:
			s.connect((host, port))
			s.settimeout(1)
			data, addr = s.recvfrom(2048)
						
			if data:
				self.showAnyMessage("Message <"+str(data)+"> received from: "+str(addr))
			else:
				self.session.openWithCallback(self.showMainMenuCallback, MessageBox, "No data to show", MessageBox.TYPE_ERROR)

		except socket.error, msg:
			self.session.openWithCallback(self.showMainMenuCallback, MessageBox, "Socket error: "+str(msg), MessageBox.TYPE_ERROR)
		except socket.timeout, msg:
			self.session.openWithCallback(self.showMainMenuCallback, MessageBox, "Socket error: "+str(msg), MessageBox.TYPE_ERROR)
		
							
	def showAnyMessage(self, message):
		self.session.openWithCallback(self.showMainMenuCallback, MessageBox, ""+str(message), MessageBox.TYPE_INFO)
		
	def showMainMenuCallback(self, result):
		if result:
			self.showMainMenu()
		else:
			self.clean()
			
		
	def showCurrentService(self):
		
		try:
			service = self.session.nav.getCurrentService()
			ref = self.session.nav.getCurrentlyPlayingServiceReference()
			refstr = ref.toString()
			info = service.info()
			event=info.getEvent(0)
			servicename=info.getName()
		
			iidee, name, description, begin, end = self.parseEvent(event)
			starttime = strftime("%Y.%m.%d %H:%M:%S", time.localtime(begin))
			endtime = strftime("%Y.%m.%d %H:%M:%S", time.localtime(end))
		
			self.showAnyMessage("Channel:"+str(servicename)+
					"\nProgram: "+str(name)+
					"\nID: "+str(iidee)+
					"\nRefstr: "+str(refstr)+
					"\nDescription: "+str(description)+
					"\nStart Time:"+str(starttime)+
					"\nEnd Time:"+str(endtime))
		except:
			self.showAnyMessage("Service not found.")
	
	def updateEPG(self):
		epg_data=[]
					
		try:
			test = [ (service.ref.toString(), 0, -1, -1) for service in Services ]
			test.insert(0, 'XRIBDTSEN')
			
			#case '0': // PyLong 0
			#case 'X': // index-1
			#case 'I': // Event Id
			#case 'B': // Event Begin Time
			#case 'D': // Event Duration
			#case 'T': // Event Title
			#case 'S': // Event Short Description
			#case 'E': // Event Extended Description
			#case 'R': // service reference string
			#case 'n': // short service name
			#case 'N': // service name
			
			epg_data = self.queryEPG(test)
			
			if epg_data:
				self.fileWriter(epg_data)
				#fileWriter = fileWriterThread(epg_data)	#Creating fileWriter thread
				#fileWriter.start()
				self.session.openWithCallback(self.showMainMenuCallback, MessageBox, "EPG data Updated.", MessageBox.TYPE_INFO, timeout=5)
				
			else:
				self.session.openWithCallback(self.showMainMenuCallback, MessageBox, "EPG data not found.", MessageBox.TYPE_ERROR)
				
		except:
			self.session.openWithCallback(self.showMainMenuCallback, MessageBox, "Updating EPG data failed.", MessageBox.TYPE_ERROR)

			
	def queryEPG(self, list, buildFunc=None):
		
		if self.epgcache is not None:
			if buildFunc is not None:
				return self.epgcache.lookupEvent(list, buildFunc)
			else:
				return self.epgcache.lookupEvent(list)
		return [ ]


#Threadi bugittaa, disabloin sen. t. Samuli
#class fileWriterThread(threading.Thread):
#	def __init__ (self, epgdata):
#		threading.Thread.__init__(self)
#
#		self.epgdata = epgdata
#		self.status = -1
#
#		udp_port = 6788
#		host = '127.0.0.1'
#		s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#		port = int(udp_port)
#		s.connect((host, port))
#		s.sendall("Thread: Creating pipe")
#	
#	def run(self):

	
	def fileWriter(self, epgdata):
		
		self.epgdata = epgdata
		self.list = [ ]
		tmp_list = None
		servicename = ""
		eventname = ""
		eventid = ""
		shortdscr = ""
		longdscr = ""
		duration = ""
		starttime = ""
		endtime = ""
				
		for x in self.epgdata:
			eventid = str(x[1])
			starttime = strftime("%Y.%m.%d %H:%M:%S", time.localtime(x[2]))
			endtime = strftime("%Y.%m.%d %H:%M:%S", time.localtime(x[2] + x[3]))
			duration = str(x[3]/60)
			eventname = x[4]
			#shortdscr = x[5]
			#longdscr = x[6]
			servicename = x[7]
			self.list.append((servicename, eventid, eventname, starttime, endtime, duration))

		doc = Document()
		dbElement = doc.createElement("database")
		doc.appendChild(dbElement)

		for element in self.list:

			programElement = doc.createElement("program")
			dbElement.appendChild(programElement)
		
			channelElement = doc.createElement("channel")
			programElement.appendChild(channelElement)
			text = doc.createTextNode(element[0])
			channelElement.appendChild(text)

			idElement = doc.createElement("id")
			programElement.appendChild(idElement)
			text = doc.createTextNode(element[1])
			idElement.appendChild(text)
			
			nameElement = doc.createElement("name")
			programElement.appendChild(nameElement)
			text = doc.createTextNode(element[2])
			nameElement.appendChild(text)
		
			startElement = doc.createElement("start")
			programElement.appendChild(startElement)
			text = doc.createTextNode(element[3])
			startElement.appendChild(text)
		
			endElement = doc.createElement("end")
			programElement.appendChild(endElement)
			text = doc.createTextNode(element[4])
			endElement.appendChild(text)
		
			durationElement = doc.createElement("duration")
			programElement.appendChild(durationElement)
			text = doc.createTextNode(element[5])
			durationElement.appendChild(text)
	
		try:
			f = open('/media/hdd/osamiepg.xml', 'w')
			f.write(doc.toprettyxml(indent="\t"))
			f.close()
		
			s.connect((host, port))
			s.sendall("EPG updated")
			#self.sendMessage("EPG updated")
			#self.session.open(MessageBox, _("EPG updated"), MessageBox.TYPE_INFO, timeout=5)
		
			#self.showAnyMessage("EPG updated")
		except:
			s.connect((host, port))
			s.sendall("EPG update error")
			#self.session.open(MessageBox, _("Updating EPG data failed while writing file."), MessageBox.TYPE_INFO, timeout=5)
			#self.showAnyMessage("Updating EPG data failed while writing file.")


	def removeTimer(self, timer):
		timer.afterEvent = AFTEREVENT.NONE
		self.session.nav.RecordTimer.removeEntry(timer)
		self["key_green"].setText(_("Add timer"))
		self.key_green_choice = self.ADD_TIMER
		self.showMainMenu()
	
	def timerAdd(self, eventiidee, channelname):
		eventid = eventiidee
		channel = channelname
		
		self["list"] = EPGList(type= 1, timer = self.session.nav.RecordTimer)
		
		event = self.getRightEvent(eventid, channel)
		if event:
			servicename = event[7]
			refstr = event[0]
			service = ServiceReference(refstr)
							
			event = self.epgcache.lookupEventId(service.ref, eventid)

			serviceref = service.ref

			
			if isinstance(serviceref, eServiceReference):
				serviceref = ServiceReference(serviceref)			
			
			for timer in self.session.nav.RecordTimer.timer_list:
				if timer.eit == eventid and timer.service_ref.ref.toString() == refstr:
					cb_func = lambda ret : not ret or self.removeTimer(timer)
					self.session.openWithCallback(cb_func, MessageBox, _("Do you really want to delete %s?") % event.getEventName())
					break

			newEntry = RecordTimerEntry(serviceref, checkOldTimers = True, *parseEvent(event))
			self.session.openWithCallback(self.finishedAdd, TimerEntry, newEntry)
		else:
			self.showAnyMessage("Cannot find event by id:"+str(eventid)+" and channel:"+str(channel))
			

	def finishedAdd(self, answer):
		if answer[0]:
			entry = answer[1]
			simulTimerList = self.session.nav.RecordTimer.record(entry)
			if simulTimerList is not None:
				for x in simulTimerList:
					if x.setAutoincreaseEnd(entry):
						self.session.nav.RecordTimer.timeChanged(x)
				simulTimerList = self.session.nav.RecordTimer.record(entry)
				if simulTimerList is not None:
					self.session.openWithCallback(self.finishSanityCorrection, TimerSanityConflict, simulTimerList)
			self["key_green"].setText(_("Remove timer"))
			self.key_green_choice = self.REMOVE_TIMER
		else:
			self["key_green"].setText(_("Add timer"))
			self.key_green_choice = self.ADD_TIMER
				
	def finishSanityCorrection(self, answer):
		self.finishedAdd(answer)
		
	def getRightEvent(self, eventId, Channel):
		
		epg_data=[]
		eventid = eventId
		channel = Channel			
					
		try:
			test = [ (service.ref.toString(), 0, -1, -1) for service in Services ]
			test.insert(0, 'XRIBDTSEN')
			epg_data = self.queryEPG(test)
		except:
			self.session.openWithCallback(self.showMainMenuCallback, MessageBox, "Error.", MessageBox.TYPE_ERROR)

		event = None
		currentid = ""
		thischannel = ""
		for x in epg_data:
			thischannel = str(x[7])
			if thischannel == channel:
				currentid = str(x[1])
				if currentid == str(eventid):
					event = x
		return event
		
	def startInstantRecording(self, limitEvent = False):
		serviceref = self.session.nav.getCurrentlyPlayingServiceReference()

		# try to get event info
		event = None
		try:
			service = self.session.nav.getCurrentService()
			epg = eEPGCache.getInstance()
			event = epg.lookupEventTime(serviceref, -1, 0)
			if event is None:
				info = service.info()
				ev = info.getEvent(0)
				event = ev
		except:
			pass

		begin = int(time())
		end = begin + 3600	# dummy
		name = "instant record"
		description = ""
		eventid = None

		if event is not None:
			curEvent = parseEvent(event)
			name = curEvent[2]
			description = curEvent[3]
			eventid = curEvent[4]
			if limitEvent:
				end = curEvent[1]
		else:
			if limitEvent:
				self.session.open(MessageBox, _("No event info found, recording indefinitely."), MessageBox.TYPE_INFO)

		if isinstance(serviceref, eServiceReference):
			serviceref = ServiceReference(serviceref)

		recording = RecordTimerEntry(serviceref, begin, end, name, description, eventid, dirname = preferredInstantRecordPath())
		recording.dontSave = True
		
		if event is None or limitEvent == False:
			recording.autoincrease = True
			if recording.setAutoincreaseEnd():
				self.session.nav.RecordTimer.record(recording)
				self.recording.append(recording)
				self.showMainMenu()
		else:
				simulTimerList = self.session.nav.RecordTimer.record(recording)
				if simulTimerList is not None:	# conflict with other recording
					name = simulTimerList[1].name
					name_date = ' '.join((name, strftime('%c', localtime(simulTimerList[1].begin))))
					print "[TIMER] conflicts with", name_date
					recording.autoincrease = True	# start with max available length, then increment
					if recording.setAutoincreaseEnd():
						self.session.nav.RecordTimer.record(recording)
						self.recording.append(recording)
						self.session.open(MessageBox, _("Record time limited due to conflicting timer %s") % name_date, MessageBox.TYPE_INFO)
					else:
						self.session.open(MessageBox, _("Couldn't record due to conflicting timer %s") % name, MessageBox.TYPE_INFO)
					recording.autoincrease = False
				else:
					self.recording.append(recording)
					self.showMainMenu()


	def stopCurrentRecording(self, entry = -1):
		if entry is not None and entry != -1:
			self.session.nav.RecordTimer.removeEntry(self.recording[entry])
			self.recording.remove(self.recording[entry])
	
	#Pause the service		
	def pause(self):
		try:
			s.connect((host, port))
			s.sendall("Pause")
						
			if not self.timeshift_enabled:
				self.startTimeshift()
				self.timeshift_enabled = 1
			else:
				self.activateTimeshiftEnd(False)
								
			#self.showMainMenu()
		except:
			pass #self.showAnyMessage("Error occurred!")
	
	#Continue the service
	def play(self):
			
		try:
			s.connect((host, port))
			s.sendall("Play")
						
			#if self.timeshift_enabled:
			self.activateTimeshiftEnd(False)
				
			#self.showMainMenu()
		except:
			pass #self.showAnyMessage("Error occurred!")
	
	#Forward the service		
	def forward(self):
			
		try:
			s.connect((host, port))
			s.sendall("Forward")
						
			#if self.timeshift_enabled:
			self.seekFwd()
			#self.showMainMenu()
		except:
			pass #self.showAnyMessage("Error occurred!")

	def receiveCall(self, data):
		self.info = data.split(', ')
		self.caller = self.info[1]
		self.number = self.info[2]
		self.callInfo = "<Phone Call>\n\nCaller: "+self.caller+"\nPhone number: "+self.number
		self.session.open(MessageBox, _(self.callInfo), MessageBox.TYPE_INFO, timeout=8)
		self.pause()
			
	def receiveMessage(self, data):
		self.info = data.split(', ')
		self.sender = self.info[1]
		self.number = self.info[2]
		self.message = self.info[3]
		self.messageInfo = "<Text Message>\n\nSender: "+self.sender+"\nPhone number: "+self.number+"\nMessage: "+self.message
		self.session.openWithCallback(self.myTimeoutCallback, MessageBox, _(self.messageInfo), MessageBox.TYPE_INFO, timeout=8)
		#self.session.open(MessageBox, _(self.messageInfo), MessageBox.TYPE_INFO, timeout=8)
		self.pause()
			
	def myTimeoutCallback(self, result):
		self.play()
			
	def channelUp(self):
		s.connect((host, port))
		s.sendall("ChannelUp")
		self.zapUp()
	
	def channelDown(self):
		s.connect((host, port))
		s.sendall("ChannelDown")
		self.zapDown()
	
	def receiveSocketMsg(self):
		data, addr = s.recvfrom(2048)
		return data
	
	def sendSocketMsg(self, msg):
		s.connect((host, port))
		s.sendall(str(msg))
			
	
class SocketThread(threading.Thread):
		
	def __init__ (self, Session, jokuVaan):
		threading.Thread.__init__(self)

		self.status = -1
		self.session = Session
		self.joku = jokuVaan
		"""
		udp_port = 6788
		host = '127.0.0.1'
		s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		port = int(udp_port)
		s.connect((host, port))
		s.sendall("Thread: Creating pipe")
		"""

	def run(self):
		while 1:	

			#s.settimeout(1)
			data = self.joku.receiveSocketMsg()
						
			if data:
				
				if str(data).startswith('Pause'):
					self.joku.pause()

				elif str(data).startswith('Play'):
					self.joku.play()

				elif str(data).startswith('Forward'):
					self.joku.forward()
								
				elif str(data).startswith('Call'):
					self.joku.receiveCall(str(data))
								
				elif str(data).startswith('TextMessage'):
					self.joku.receiveMessage(str(data))
								
				elif str(data).startswith('ChannelUp'):
					self.joku.channelUp()

				elif str(data).startswith('ChannelDown'):
					self.joku.channelDown()
														
				else:
					self.joku.sendSocketMsg("----------------------")
								
			else:
				self.joku.sendSocketMsg("----------------------")



